package com.demo.common.threadpool.config;

import com.demo.common.threadpool.annotation.EnableFxwThPool;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.*;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.annotation.Resource;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Author：DayDayUp
 * @Create：2023/3/29 10:31
 * @Enable 开启多线程
 */

@EnableAsync
@Configuration
@ConditionalOnBean(annotation = EnableFxwThPool.class)
@EnableConfigurationProperties(ThreadPoolProperties.class)
@ConditionalOnProperty(prefix = ThreadPoolProperties.PREFIX, name = "enabled", havingValue = "true" ,matchIfMissing = true)
public class ThreadPoolAutoConfig {
    @Resource
    private ThreadPoolProperties threadPoolProperties;

    @Bean("asyncTaskExecutor")
    public Executor asyncTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置核心线程数
        executor.setCorePoolSize(threadPoolProperties.getCorePoolSize());
        // 设置最大线程数
        executor.setMaxPoolSize(threadPoolProperties.getMaxPoolSize());
        // 配置队列大小
        executor.setQueueCapacity(threadPoolProperties.getQueueCapacity());
        // 设置线程空闲时间，当超过核心线程之外的线程在空闲到达之后会被销毁（秒）
        executor.setKeepAliveSeconds(threadPoolProperties.getKeepAliveSeconds());
        // 设置默认线程名称
        executor.setThreadNamePrefix(threadPoolProperties.getThreadNamePrefix());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        //执行初始化
        executor.initialize();
        return executor;
    }

}

